<template>
    <div class="learn-relevance-students">
        <el-card shadow="never" v-loading="loading">
            <div class="title mb-4">该指派学习内容的关联导师清单</div>
            <div class="name-list flex flex-wrap mb-8">
                <div v-for="item in teacher" :key="item.id" class="name-item">{{ item.name }}</div>
            </div>
            <div class="title mb-4">待指派学习内容</div>
            <div class="desc-title">学习清单或学习主题名</div>
            <div class="desc">北京产品部中级产品经理高潜学习目标</div>

            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane
                    v-for="item in teacher"
                    :key="item.id"
                    :label="item.name"
                    :name="item.num"></el-tab-pane>
            </el-tabs>

            <div class="transfer">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <div class="choose">
                            <div class="choose-header">
                                <el-checkbox
                                    @change="allCheckFn($event, student, 'studentChoose', true)"
                                    v-model="studentCheck">
                                    已指派用户 ({{ student.length }}）
                                </el-checkbox>
                                <el-button
                                    :disabled="!studentChoose.length || +activeName !== adminId"
                                    @click="addStudent('delete', 'studentChoose')"
                                    type="primary"
                                    size="mini">移除所选</el-button>
                            </div>
                            <div class="choose-content">
                                <div class="choose-item" v-for="item in student" :key="item.id">
                                    <el-checkbox
                                        :disabled="item.disabled"
                                        @change="checkChange($event, item, student, 'studentCheck', 'studentChoose')"
                                        v-model="item.check"></el-checkbox>
                                    <img class="user-img" :src="item.avatar || defaultAvatar" alt="">
                                    <div class="user-name">{{ item.name }}</div>
                                    <span class="ml-auto"></span>
                                    <el-button
                                        @click="delAssign(item.id)"
                                        v-if="!item.disabled"
                                        type="text"
                                        class="delete">移除</el-button>
                                </div>
                            </div>
                        </div>
                    </el-col>
                    <el-col :span="12">
                        <div class="choose" v-if="+activeName === $store.state.my.id">
                            <div class="choose-header">
                                <el-checkbox
                                    @change="allCheckFn($event, allStudent, 'allStudentChoose')"
                                    v-model="allStudentCheck">
                                    可指派用户 ({{ allStudent.length }}）
                                </el-checkbox>
                                <el-button
                                    :disabled="!allStudentChoose.length"
                                    @click="addStudent('add', 'allStudentChoose')"
                                    type="primary"
                                    size="mini">指派所选</el-button>
                            </div>
                            <div class="choose-content">
                                <div class="choose-item" v-for="item in allStudent" :key="item.id">
                                    <el-checkbox
                                        :disabled="item.disabled"
                                        @change="checkChange($event,
                                                item, allStudent, 'allStudentCheck', 'allStudentChoose')"
                                        v-model="item.check"></el-checkbox>
                                    <img class="user-img" :src="item.avatar || defaultAvatar" alt="">
                                    <div class="user-name">{{ item.name }}</div>
                                </div>
                            </div>
                        </div>
                    </el-col>
                </el-row>
            </div>
        </el-card>
    </div>
</template>

<script>
import { Tabs, TabPane } from 'element-ui';

export default {
    components: {
        ElTabs: Tabs,
        ElTabPane: TabPane,
    },
    data() {
        return {
            type: 'lable',
            adminId: '',
            loading: false,
            labelId: '',

            activeName: '',
            data: [],

            teacher: [],

            student: [],
            studentCheck: false,
            studentChoose: [],

            allStudent: [],
            allStudentCheck: false,
            allStudentChoose: [],

            configStatus: {
                NOT_ASSOCIATED: 0,
                UN_ASSIGNED: 1,
                UN_ASSIGNED_SELF: 2,
                ASSIGNED: 3,
                ASSIGNED_SELF: 4,
            },

            defaultAvatar: require('@/assets/images/menu-six.png'),
        };
    },
    methods: {
        handleClick() {
            if (+this.activeName === this.adminId) {
                this.getAllStudent();
            } else this.getStudent(+this.activeName);
        },

        allCheckFn(e, itemList, chooseArr, kind) {
            let chooseList = [...this[chooseArr]];
            itemList.map(item => {
                if (this.configStatus[item.status] && !kind) return item;
                if (this.configStatus[item.status] >= 3 && kind) return item;

                if (e) {
                    if (!chooseList.length) chooseList.push(item.id);
                    else {
                        const itemId = chooseList.indexOf(item.id) === -1 ? item.id : null;
                        if (itemId) chooseList.push(itemId);
                    }
                }

                item.check = e;
                return item;
            });

            if (!e) chooseList = [];

            this[chooseArr] = chooseList;
        },

        checkChange(e, item, itemList, allCheck, choose) {
            let chooseNum = 0;
            for (const val of itemList) {
                if (val.check) chooseNum += 1;
            }

            const chooseData = this[choose];
            if (!chooseData.length) {
                chooseData.push(item.id);
            } else {
                let index;

                chooseData.forEach((v, i) => {
                    if (v === item.id) index = i;
                });

                if (typeof index === 'number') {
                    chooseData.splice(index, 1);
                } else chooseData.push(item.id);
            }

            this[allCheck] = chooseNum === itemList.length;
        },

        /**
         * 添加关联、移除关联
        */
        addStudent(type, chooseText) {
            const chooseList = [...this[chooseText]];
            const list = [...this.student];

            let formData;

            if (type === 'add') {
                for (const item of this.allStudent) {
                    if (this.configStatus[item.status] === 2) chooseList.push(item.id);
                }
                formData = chooseList.sort();
            } else {
                const associated = [];
                for (const val of list) {
                    if (this.configStatus[val.status] === 2 && chooseList.indexOf(val.id) === -1) {
                        associated.push(val.id);
                    }
                }
                formData = associated.sort();
            }

            this.loading = true;
            API.post(`task/${this.type}/linked/${this.labelId}`, formData).then(() => {
                $ele.$message.success(`${type === 'add' ? '关联' : '移除'}成功`);
                this.getAllStudent();
            }).finally(() => this.loading = false);
        },

        /**
         * 个体移除关联
         * 移除关联
        */
        delAssign(id) {
            const list = [...this.student];
            const associated = [];
            for (const val of list) {
                if (this.configStatus[val.status] === 2 && id !== val.id) {
                    associated.push(val.id);
                }
            }

            this.loading = true;
            API.post(`task/${this.type}/linked/${this.labelId}`, associated.sort()).then(() => {
                $ele.$message.success('移除成功');
                this.getAllStudent();
            }).finally(() => this.loading = false);
        },

        /**
         * 获取老师列表
        */
        getTeacher() {
            API.get('task/lable/admins').then(res => {
                this.teacher = [...res].map(item => {
                    item.num = `${item.id}`;
                    return item;
                });
                this.activeName = String(this.adminId);
            });
        },

        /**
         * 获取教师已关联学员
        */
        getStudent() {
            API.get(`task/${this.type}/users/${this.activeName}/${this.labelId}`).then(res => {
                this.studentCheck = false;
                this.studentChoose = [];

                this.student = [...res].map(item => {
                    item.check = this.configStatus[item.status] >= 3;
                    item.disabled = this.configStatus[item.status] >= 3;
                    return item;
                });
            });
        },

        /**
         * 获取该公司下所有学员
        */
        getAllStudent() {
            API.get(`task/${this.type}/all-users/${this.labelId}`).then(res => {
                this.allStudentCheck = false;
                this.allStudentChoose = [];

                this.allStudent = [...res].map(item => {
                    item.check = !!this.configStatus[item.status];
                    item.disabled = !!this.configStatus[item.status];
                    return item;
                });
            }).finally(() => {
                this.getStudent();
            });
        },
    },
    mounted() {
        this.type = this.$route.params.type || 'lable';
        // 学习路径 || 学习主题 id
        this.labelId = this.$route.query.labelId;

        // 登录系统账户的id
        this.adminId = this.$store.state.my.id;

        this.getTeacher();
        if (this.labelId) {
            this.getAllStudent();
        }
    },
};
</script>

<style lang="scss">
.learn-relevance-students {
    .title {
        padding: 14px 0 14px 20px;
        font-size: 14px;
        color: #9b9b9b;
        background: #fafafa;
    }

    .name-item {
        min-width: 100px;
        width: fit-content;
        height: 44px;
        line-height: 44px;
        text-align: center;
        padding: 0 10px;
        box-shadow: 0 0 6px 2px #dddfe6;
        margin-right: 10px;
        color: #55a8ff;
        font-size: 20px;
        box-sizing: border-box;
        border-radius: 4px;
        margin-bottom: 10px;
    }

    .desc-title {
        font-size: 24px;
        color: #606266;
        margin-bottom: 5px;
        font-weight: 600;
    }

    .desc {
        font-size: 14px;
        color: #b4b4b4;
        margin-bottom: 20px;
    }

    .choose {
        width: 100%;
        box-shadow: 2px 2px 6px 2px #dddfe6;
        border-radius: 4px;
        overflow: hidden;

        &-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            height: 44px;
            background: #f7f7f7;
            padding: 0 16px;
        }

        &-content {
            height: 560px;
            overflow-y: auto;
            padding-top: 20px;
        }

        &-item {
            display: flex;
            align-items: center;
            height: 40px;
            transition: all .1s;
            padding: 0 16px;

            .delete {
                display: none;
            }

            &:hover {
                background: #ecf5ff;

                .delete {
                    display: block;
                }
            }

            .el-checkbox {
                margin-right: 10px;
            }

            .user-img {
                width: 26px;
                height: 26px;
                margin-right: 10px;
                object-fit: contain;
            }

            .user-name {
                font-size: 14px;
                color: #252525;
            }
        }

        .el-checkbox__inner {
            border-radius: 50%;
        }
    }
}
</style>
